import { createRouter, createWebHistory } from 'vue-router'

import nProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { useUserStore } from '@/stores'

nProgress.configure({ easing: 'ease', speed: 500, showSpinner: false })

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      component: () => import('@/views/Layout/layout.vue'),
      meta: {
        requireAuth: true // 需要登录才能访问
      },
      children: [
        {
          path: '',
          component: () => import('@/views/Home/home.vue')
        },
        {
          path: '/personal',
          component: () => import('@/views/Personal/personal.vue')
        },
        {
          path: '/forum',
          component: () => import('@/views/Forum/forum.vue')
        },
        {
          path: '/pet',
          component: () => import('@/views/Pet/pet.vue')
        },
        {
          path: '/location/:id',
          component: () => import('@/views/Location/location.vue')
        },
        {
          path: 'mynote',
          component: () => import('@/views/Mynote/mynote.vue')
        },
        {
          path: '/order',
          component: () => import('@/views/Order/order.vue')
        },
      ]
    },
    {
      path: '/pay',
      component: () => import('@/views/Pay/pay.vue')
    },
    {
      path: '/login',
      component: () => import('@/views/Login/login.vue'),
      meta: {
        requireGuest: true // 需要游客才能访问
      }
    },
    {
      path: '/forget',
      component: () => import('@/views/Forget/forget.vue'),
      meta: {
        requireGuest: true // 需要游客才能访问
      }
    },
    {
      path: '/:catchAll(.*)',
      component: () => import('@/views/NotFound/404.vue')
    }
  ]
})

router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  nProgress.start()

  if (to.matched.some(record => record.meta.requireAuth)) {
    if (!userStore.token) {
      next('/login')
    } else {
      next()
    }
  } else if (to.matched.some(record => record.meta.requireGuest)) {
    if (userStore.token) {
      next({
        path: '/'
      })
    } else {
      next()
    }
  } else {    
    next()
  }
})

router.afterEach(() => {
  nProgress.done()
})

export default router
